//
//  LoginViewController.m
//  project
//
//  Created by 李腾昊 on 2017/10/20.
//  Copyright © 2017年 Macmini. All rights reserved.
//

#import "LoginViewController.h"
#import "UIImage+TBCityIconFont.h"
#import "TBCityIconFont.h"
#import "FindPasswordViewController.h"
#import "CLTabBarViewController.h"
#import "RegistViewController.h"
#import "ZWTools.h"
#import "MBProgressHUD+KR.h"
#import "ConfriusernameViewController.h"
#import "ZWUserModel.h"
#import "NSObject+MJExtension.h"
#import "PrefixHeader.pch"
#import "AppDelegate.h"
#define RONGCLOUD_IM_APPKEY @"pkfcgjstpkh88" //请换成您的appkey
//text

@interface LoginViewController ()

@property (weak, nonatomic) IBOutlet UITextField *phoneTF;

@property (weak, nonatomic) IBOutlet UITextField *passwordTF;

@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;
@property (weak, nonatomic) IBOutlet UIImageView *usernameIcon;
@property (weak, nonatomic) IBOutlet UIImageView *passwordIcon;
@property (weak, nonatomic) IBOutlet UIButton *miwenBtn;
/////////////////gaidong 
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"登录";
    [self configurImage];
   
    [self confriNavbar];
}

- (void)confriNavbar {
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"返回" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(clickButton) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem =leftBarButtonItem;
}
- (void)clickButton {
    
    CLTabBarViewController *clTVC = [[CLTabBarViewController alloc] init];
    [UIApplication sharedApplication].keyWindow.rootViewController = clTVC;
}

- (void)configurImage {
    
     self.iconImageView.image = [ UIImage iconWithInfo:TBCityIconInfoMake(@"\U0000e610",150,[UIColor blueColor])];
    self.usernameIcon.image = [ UIImage iconWithInfo:TBCityIconInfoMake(@"\U0000e601",13, [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.2/1.0])];
    self.passwordIcon.image = [UIImage iconWithInfo:TBCityIconInfoMake(@"\U0000e6ea", 18, [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.2/1.0])];
    [self.miwenBtn setBackgroundImage:[UIImage iconWithInfo:TBCityIconInfoMake(@"\U0000e636",20 , [UIColor colorWithRed:199/255.0 green:199/255.0 blue:205/255.0 alpha:1/1.0])] forState:UIControlStateNormal];
}
- (IBAction)login:(id)sender {
    
    //判断输入的用户名是手机号还是邮箱(手机号，调用用户登录接口/邮箱，调用中介登录接口)
    if ([self.phoneTF.text containsString:@"com"]) {
        [self icLogin]; //中介
    } else {
        [self ucLogin]; //用户
    }
    
}

#pragma mark - 用户登录
- (void)ucLogin {
    
    NSMutableDictionary *requestParameter = [NSMutableDictionary dictionary];
    requestParameter[@"phone"] = self.phoneTF.text;
    requestParameter[@"password"] = self.passwordTF.text;
    
    ZWTools *tools = [ZWTools sharedManager];
    [tools login:requestParameter sucessBlock:^(id jsonResponse) {
         NSLog(@"%@", jsonResponse);
                ZWUserModel *model = [ZWUserModel parse:jsonResponse[@"data"]];
                model.token = token;
                loginuserInfo = model;
                 [NSKeyedArchiver archiveRootObject:loginuserInfo toFile:PATH_USERINFO_DATA];
       
       
      
        NSString *nickname =     jsonResponse[@"data"][@"nickName"];
        NSLog(@"%@", nickname);
        if ([nickname isEqual:[NSNull null]]) {
            ConfriusernameViewController *confriusernameVC = [ConfriusernameViewController new];
            NSDictionary *data = [jsonResponse objectForKey:@"data"];
            confriusernameVC.userid = [[data objectForKey:@"id"] integerValue]; //传id
            NSLog(@"%ld", (long)confriusernameVC.userid);
            [self.navigationController pushViewController:confriusernameVC animated:YES];
            
            
        } else {
          //  74f566735a25f9e16a5daa26a20a8741
            CLTabBarViewController *clTVC = [[CLTabBarViewController alloc] init];
            [UIApplication sharedApplication].keyWindow.rootViewController = clTVC;
            [self loginRongCloud];
             
        }
        
   
    } Error:^(id jsonResponse) {
        
    }];
}

/**
 *登录融云
 *
 */
-(void)loginRongCloud
{
      [[RCIM sharedRCIM] initWithAppKey:RONGCLOUD_IM_APPKEY];
    //登录融云服务器,开始阶段可以先从融云API调试网站获取，之后token需要通过服务器到融云服务器取。
    NSString*token=@"Cy0jErlwtmgJ8rB3ZO1g7QQo6oi3mCmwtYGl2yIkpUNxCwMQPb8N4ZD36D0QEI0BE4offeXIacurRyug31N0OQ==";
    [[RCIM sharedRCIM] connectWithToken:token success:^(NSString *userId) {
        //设置用户信息提供者,页面展现的用户头像及昵称都会从此代理取
        [[RCIM sharedRCIM] setUserInfoDataSource:self];
        NSLog(@"Login successfully with userId: %@.", userId);
//        dispatch_async(dispatch_get_main_queue(), ^{
//            ChatListViewController *chatListViewController = [[ChatListViewController alloc]init];
//            [self.navigationController pushViewController:chatListViewController animated:YES];
//        });
        
    } error:^(RCConnectErrorCode status) {
        NSLog(@"login error status: %ld.", (long)status);
    } tokenIncorrect:^{
        NSLog(@"token 无效 ，请确保生成token 使用的appkey 和初始化时的appkey 一致");
    }];
    
}
#pragma mark - 中介登录
- (void)icLogin {
    
    NSMutableDictionary *requestParameter = [NSMutableDictionary dictionary];
    requestParameter[@"email"] = self.phoneTF.text;
    requestParameter[@"password"] = self.passwordTF.text;
    
    ZWTools *tools = [ZWTools sharedManager];
    [tools icLogin:requestParameter sucessBlock:^(id jsonResponse) {
        
        NSInteger result = [[jsonResponse objectForKey:@"code"] integerValue];
        
        if (result == 0) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [MBProgressHUD showSuccess:@"中介登录成功"];
                is_Ic = YES;
                [self loginRongCloud];
                CLTabBarViewController *clTVC = [[CLTabBarViewController alloc] init];
                [UIApplication sharedApplication].keyWindow.rootViewController = clTVC;
                
            });
        } else if (result == 100) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [MBProgressHUD showSuccess:@"中介登录失败"];
                
                
            });
        }
        
        
    } Error:^(id jsonResponse) {
        
    }];
}

- (IBAction)clickForgetpasswordBtn:(id)sender {
    
    FindPasswordViewController *findPWVC = [[FindPasswordViewController alloc] init];
    [self.navigationController pushViewController:findPWVC animated:YES];
}

- (IBAction)regiest:(id)sender {
    
    RegistViewController *registVC = [RegistViewController new];
    [self.navigationController pushViewController:registVC animated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
